<template>
    <el-dialog
      title="审批流程"
      :visible.sync="dialogVisible"
      width="90%"
      :before-close="handleClose"
    >
      <div class="wrapper">
        <div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="开始时间">
                  <el-date-picker
                    v-model="form.start"
                    readonly
                    type="date"
                    placeholder="开始时间"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    style="width: 100%"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="截止时间">
                  <el-date-picker
                    type="date"
                    readonly
                    placeholder="截止时间"
                    value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd"
                    v-model="form.end"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="查看事由">
                  <el-input
                    type="textarea"
                    :rows="3"
                    readonly
                    placeholder="请输入内容"
                    v-model="form.applyContent"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
  
            <el-form-item label-width="10px">
              <div class="centerWarp">
                <div>
                  <el-card class="box-card">
                    <div class="nameStyle" :style="{ height: heightY }">
                      <p
                        v-for="(item, index) in dataName"
                        :key="index"
                        @click="hanldClickName(item, index)"
                        :class="{ highlight: index === personNameIndex }"
                      >
                        {{ item.personName }}
                      </p>
                    </div>
                  </el-card>
                </div>
                <div>
                  <el-card class="box-card">
                    <div
                      style="
                        width: 240px;
                        text-align: center;
                        margin-left: 5px;
                        overflow-y: scroll;
                      "
                      :style="{ height: heightY }"
                    >
                      <h2>授权表：</h2>
                      <p>{{ textValue }}</p>
                    </div>
                  </el-card>
                </div>
                <div class="left" :style="{ height: heightTree }">
                  <el-tree
                    ref="tree"
                    style="margin-left: 10px; margin-top: 5px; margin-bottom: 5px"
                    :data="treeData"
                    node-key="id"
                    :props="defaultProps"
                    highlight-current
                    @node-click="handleNodeClick"
                    :current-node-key="currentNodekey"
                    :default-expanded-keys="
                      treeData.length !== 0 ? [treeData[0].children[0]] : []
                    "
                  ></el-tree>
                </div>
                <div class="right">
                  <div class="thumbnail" :style="{ height: heightY }">
                    <el-checkbox
                      style="margin-left: 7px"
                      :indeterminate="isIndeterminate"
                      v-model="checkAll"
                      @change="handleCheckAllChange"
                    >
                      全选</el-checkbox
                    >
                    <div
                      class="image-container"
                      v-for="(cityItem, index) in imageData"
                      :key="index"
                    >
                      <el-checkbox-group
                        v-model="checkedCities"
                        @change="handleCheckedCitiesChange"
                      >
                        <el-checkbox
                          :key="cityItem.elecId"
                          :label="cityItem.elecId"
                          @change="handleCheckboxChange($event, cityItem)"
                        ></el-checkbox>
                      </el-checkbox-group>
                      <img
                        :src="cityItem.description"
                        :style="{
                          width: '140px',
                          height: '200px',
                          border:
                            index === selectedImageIndex ? '2px solid red' : '',
                        }"
                        @click="selectImage(index)"
                      />
                    </div>
                  </div>
                  <div class="bigPicture" :style="{ height: heightY }">
                    <img
                      :src="
                        selectedImageIndex !== null &&
                        imageData[selectedImageIndex]
                          ? imageData[selectedImageIndex].description
                          : ''
                      "
                      alt=""
                      style="width: 100%; height: 100%"
                    />
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <el-form-item label="反馈意见">
                  <el-input
                    type="textarea"
                    :rows="3"
                    placeholder="请输入内容"
                    v-model="returnContent"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          size="medium"
          v-if="auditStateFlag"
          type="primary"
          @click="clickAuthorization"
          >授 权</el-button
        >
        <el-button
          size="medium"
          v-if="auditStateFlag"
          type="primary"
          @click="clickApprove"
          >审批通过</el-button
        >
        <el-button
          size="medium"
          v-if="auditStateFlag"
          type="danger"
          @click="turnDown"
          >驳回申请</el-button
        >
      </span>
    </el-dialog>
  </template>
      
  <script>
  import {
    getDetail,
    authorization,
    approval,
  } from "@/api/datacentersg/achives/documentApi";
  import {
    getMaterialTree,
    clickMaterial,
    getImgFromCacheByFlag,
  } from "@/api/datacentersg/achives/documentApi";
  import store from "@/store";
  export default {
    data() {
      return {
        heightY: window.innerHeight - 320 + "px",
        heightTree: window.innerHeight - 280 + "px",
        tabPosition: "left",
        form: {
          start: "",
          end: "",
          applyContent: "",
        },
        imageData: [],
        treeData: [],
        checkedCities: [],
        defaultProps: {
          children: "children",
          label: "name",
        },
        selectedImageIndex: 0,
        currentNodekey: "",
        isIndeterminate: true,
        checkAll: false,
        textValue: "",
        oneselfData: [],
        cityItemIdAll: [],
        dialogVisible: false,
        row: null,
        dataName: [
          {
            personName: "张三",
          },
        ],
        rowItem: null,
        returnContent: "",
        applyId: "",
        personNameIndex: 0,
        materialid: "1",
        description: "",
        name: "",
        idCard: "",
        auditState: null,
        auditStateFlag: false,
        valueFlag: false,
        textsToAdd: [],
      };
    },
    created() {},
    methods: {
      init(row) {
        this.dialogVisible = true;
        this.row = row;
        this.personNameIndex = 0;
        this.textsToAdd = []
        this.textValue = "";
  
        this.getListDetail();
        this.getMaterialTree();
      },
      //详情
      getListDetail() {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          data: {
            applyId: this.row.applyId,
          },
        };
        getDetail(params).then((result) => {
          if (result.result) {
            this.applyId = result.resultdata.data.applyId;
            this.form.start = result.resultdata.data.addDate;
            this.form.end = result.resultdata.data.endDate;
            this.form.applyContent = result.resultdata.data.applyContent;
            this.returnContent = result.resultdata.data.returnContent;
            this.auditState = result.resultdata.data.auditState;
            if (this.auditState === 1) {
              this.auditStateFlag = true;
            } else {
              this.auditStateFlag = false;
            }
            this.dataName = result.resultdata.data.personList;
            this.name = this.dataName[0].personName;
            this.idCard = this.dataName[0].idCard;
            this.checkedCities = []; // 初始化为一个空数组
            this.isIndeterminate = true;
            this.checkAll = false;
            if (this.dataName[0].empowerLable === "全部") {
              this.isIndeterminate = false;
              this.checkAll = true;
              this.imageData.forEach((itemImage) => {
                this.checkedCities.push(itemImage.elecId);
              });
            } else {
              this.setTreeDataFun(this.dataName[0])
            }
            this.textValue = this.dataName[0].empowerLable;
            this.getMaterialTree();
          }
        });
      },
      // tree树的数据
      getMaterialTree() {
        const params = {
          name: "江　玮",
          idCard: "370111198001010123", //身份证号
        };
        getMaterialTree(params).then((result) => {
          if (result.data.res_code === "0000") {
            this.treeData = result.data.res_data;
            this.handleNodeClick(this.treeData[0].children[0]); // 默认展示第一个目录下的图片
  
            this.dialogVisible = true;
          } else if (result.data.res_code === "0001") {
            this.treeData = [];
            this.imageData = [];
            this.$message({
              message: result.data.res_msg,
              type: "warning",
            });
          }
        });
      },
      handleNodeClick(data) {
        this.oneselfData = [data];
        this.tcurnodeItem = data
        if (data.children && data.children.length > 0) {
          // 点击的是父节点，不执行任何操作
          return;
        }
        this.currentNodekey = data.id;
        this.nameTree = data.name;
        const materialid = this.materialid && this.currentNodekey;
        const params = {
          name: "江　玮",
          idCard: "370111198001010123", //身份证号
          materialid: materialid, //点击的目录ID
        };
        clickMaterial(params).then((result) => {
          if (result.code === 0) {
            this.imageData = result.data.res_data;
            //关于全选的操作
            if (this.valueFlag === false) {
              console.log(123);
            } else {
              this.checkedCities = this.imageData.map((item) => item.elecId);
            }
            
            this.checkedCities = []; // 初始化为一个空数组
            this.isIndeterminate = true;
            this.checkAll = false;
            if (this.dataName[0].empowerLable === "全部") {
              this.isIndeterminate = false;
              this.checkAll = true;
              this.imageData.forEach((itemImage) => {
                this.checkedCities.push(itemImage.elecId);
              });
            } else {
              // this.setTreeDataFun(this.dataName[0])
            }
  
            this.imageData.forEach((item, i) => {
              const paramsNew = {
                // name:this.dataName[0].personName,
                // idCard: this.dataName[0].idCard,//身份证号
                name: "江　玮",
                idCard: "370111198001010123", //身份证号
                fileName: item.fileName, //文件名
              };
              getImgFromCacheByFlag(paramsNew).then((result) => {
                if (result.code === 0) {
                  this.$set(item, "description", result.data.res_data);
                }
              });
            });
          }
        });
      },
  
      // 点击最左侧的名字树
      hanldClickName(item, index) {
        this.rowItem = item;
        this.textValue = item.empowerLable;
        this.personNameIndex = index; //设置选中的索引
        this.name = item.personName;
        this.idCard = item.idCard;
        this.getMaterialTree();
        this.textsToAdd = []
        this.textValue = "";
  
        this.checkedCities = []; // 初始化为一个空数组
        this.isIndeterminate = true;
        this.checkAll = false;
        if (this.rowItem.empowerLable === "全部") {
          this.isIndeterminate = false;
          this.checkAll = true;
          this.imageData.forEach((itemImage) => {
            this.checkedCities.push(itemImage.elecId);
          });
        } else {
          this.setTreeDataFun(item)
        }
      },
  
      // 设置选中数据
      setTreeDataFun(item) {
        try {
          const { empowerLable = ''  } = item
          const fileNames = empowerLable.split(",")
          fileNames.forEach((fileName) => {
            //将拼接的fileName和name还原
            const name = fileName.split("_")[0]; // 获取 name
            const realFileName = fileName.split("_")[1]; // 获取真正的文件名
            // 遍历this.treeData中的每一项
            this.treeData.forEach((treeItem) => {
              if(Array.isArray(treeItem.children)) {
                // 遍历该目录下的每一张图片
                treeItem.children.forEach((imageItem) => {
                  if (imageItem.name == name) {
                    // 如果图片文件名相同
                    // 查找对应的图片对象
                    this.imageData.forEach((item) => {
                      let itemFileName = item.fileName.replace(".jpg", "");
                      if (itemFileName == realFileName) {
                        this.checkedCities.push(item.elecId);
                      }
                    });
                  }
                });
              }
            });
          });
        } catch (error) {
          console.error('setTreeDataFun', error)
        }
      },
  
      handleCheckboxChange(e, item) {
        if (this.rowItem == null) {
          // this.$message({
          //   message: "请先选择授权人员",
          //   type: "warning",
          // });
          return
        }
        if (!this.tcurnodeItem) {
          // this.$message({
          //   message: "请选择相应目录树",
          //   type: "warning",
          // });
          return
        }
        this.$nextTick(() => {
          if(e === false) {
            const { name } = this.tcurnodeItem
            const { fileName } = item
            let itemFileName = name + '_' + fileName.replace(".jpg", "");
            let names = this.textValue.split(',')
            let listName = names.filter(f => f !== itemFileName)
            let texts = [...new Set(listName)]
            this.textValue = texts.join()
          }
        })
        console.log(e, item, this.tcurnodeItem)
        // this.textValue += this.textsToAdd.join()
        
      },
  
      // 全选
      handleCheckAllChange(val) {
        this.valueFlag = val;
        if (this.rowItem == null) {
          this.$message({
            message: "请先选择授权人员",
            type: "warning",
          });
        } else {
          if (val) {
            this.checkedCities = this.imageData.map((item) => item.elecId);
            console.log(this.checkedCities, "checkedCities");
            this.checkAll = true;
            this.textValue = "全部";
            this.isIndeterminate = false;
          } else {
            this.checkedCities = [];
            this.textValue = ""; // 清空文本值
          }
        }
      },
      // 勾选checkbox
      handleCheckedCitiesChange(value) {
        console.log(value, "value");
        if (this.rowItem == null) {
          this.$message({
            message: "请先选择授权人员",
            type: "warning",
          });
        } else if (this.oneselfData.length == 0) {
          this.$message({
            message: "请选择相应目录树",
            type: "warning",
          });
        } else {
          this.textsToAdd = [];
          // this.textValue = "";
          value.forEach((imageId) => {
            const image = this.imageData.find((item) => item.elecId === imageId);
            if (image) {
              console.log(this.oneselfData, "oneselfData");
              this.oneselfData.forEach((item) => {
                let text = `${item.name}_${image.fileName.replace(".jpg", "")}`;
                console.log(image.fileName, "image.fileName");
                // 判断勾选状态，如果勾选则添加文本，如果取消勾选则移除文本
                if (value.includes(imageId)) {
                  this.textsToAdd.push(text);
                } else {
                  // 如果取消勾选，则从已添加的文本数组中移除对应的文本
                  const index = this.textsToAdd.findIndex((t) => t === text);
                  if (index !== -1) {
                    this.textsToAdd.splice(index, 1);
                  }
                }
              });
            }
          });
  
          this.textValue = this.textValue + ',' + this.textsToAdd.join()
          let texts = [...new Set([...this.textValue.split(',')])]
          this.textValue = texts.join()
          this.checkedCities = this.imageData.map((item) => item.elecId);
          let checkedCount = value.length;
          this.checkAll = checkedCount === this.imageData.length;
          this.isIndeterminate =
            checkedCount > 0 && checkedCount < this.imageData.length;
        }
      },
  
      // 点击小图切换大图
      selectImage(index) {
        this.selectedImageIndex = index;
      },
      // 授权
      clickAuthorization() {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          data: {
            empowerLable: this.textValue, //将授权的图片名称和目录名称结合以逗号的形式传入这个里面
            dataId: "", //你点击授权人的id
          },
        };
        // params.data.empowerLable = this.textValue + ","
        params.data.dataId = this.rowItem.dataId;
        authorization(params).then((result) => {
          if (result.result) {
            this.$message({
              message: "授权成功",
              type: "success",
            });
            this.dialogVisible = false;
          }
        });
      },
  
      // 审批通过
      clickApprove() {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          data: {
            applyId: this.applyId,
            startDate: this.form.start,
            endDate: this.form.end,
            returnContent: this.returnContent,
            auditState: 2,
          },
        };
        approval(params).then((result) => {
          if (result.result) {
            this.$message({
              message: "审批通过",
              type: "success",
            });
            this.dialogVisible = false;
          }
        });
      },
      // 驳回申请
      turnDown() {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          data: {
            applyId: this.applyId,
            startDate: this.form.start,
            endDate: this.form.end,
            returnContent: this.returnContent,
            auditState: 3,
          },
        };
        approval(params).then((result) => {
          if (result.result) {
            this.$message({
              message: "驳回申请成功",
              type: "success",
            });
            this.dialogVisible = false;
          }
        });
      },
      handleClose() {
        this.dialogVisible = false;
      },
    },
  };
  </script>
    
  <style scoped>
  .wrapper {
    width: 100vw;
    height: 100vh;
  }
  .left {
    float: left;
    margin-left: 5px;
    background: #f7f2ec;
    width: 18.417vw;
    overflow-y: scroll;
  }
  .nameStyle {
    text-align: center;
    font-size: 18px;
    color: #409eff;
    overflow-y: scroll;
  }
  .nameStyle p {
    padding: 5px;
    height: 40px;
  }
  .highlight {
    background-color: #c6e2ff;
    padding: 5px;
    height: 40px;
  }
  .right {
    float: left;
    margin-left: 15px;
    background: #f7f2ec;
  }
  .thumbnail {
    width: 205px;
    overflow-y: scroll;
    float: left;
    margin-bottom: 5px;
    background: #fff;
  }
  .image-container {
    display: flex;
    padding-right: 0.521vw;
    margin-top: 5px;
    justify-content: space-around;
  }
  .image-container /deep/.el-checkbox__label {
    display: none;
  }
  
  .bigPicture {
    float: left;
    width: 600px;
    margin-bottom: 5px;
    margin-right: 10px;
    background: #fff;
    margin-left: 10px;
  }
  >>> .el-tree-node__content {
    height: 60px;
  }
  .centerWarp {
    display: flex;
  }
  /deep/ .el-tree > .el-tree-node > .el-tree-node__content {
    font-weight: 900;
    background: #cfe5fc;
  }
  /deep/
    .el-tree
    > .el-tree-node
    > .el-tree-node__children
    > .el-tree-node
    > .el-tree-node__content
    > .el-tree-node__label {
    font-weight: 700;
  }
  /deep/.el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background: #6baef1;
  }
  
  >>> .el-tree-node__content {
    /* background-color: #CFE5FC; */
    margin-top: 2px;
  }
  </style>